﻿using DataBase.DBmodels;
using DataBase.Utils;
using GalaSoft.MvvmLight.Command;
using GreenXi.Help;
using GreenXi.Model;
using GreenXi.Pages.Power;
using Microsoft.EntityFrameworkCore;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Input;
using Util;
using Util.Model;
using MessageBox = System.Windows.MessageBox;

namespace GreenXi.ViewModel
{
    public class ProductionViewModel2 : ProductionModel
    {
        public static int Id = 0;
  

        public void Init()
        {
            if (Multi != null&&Multi.Count>0) {
                CylinderNo = "";
                foreach (var item in Multi) {
                    if (item.IsCheck)
                    {
                        CylinderNo += item.ID + ",";
                    }
                }
            }
            var Productions = MyDbContext.Instance.GetProductionSelect(CraftId.ToString(), CylinderNo,2, StartTime, EndTime);
            CraftList = new (MyDbContext.GetCraftViewByType(2));
           

            OPDate = Productions;
            if (OPDate != null && OPDate.Count > 0)
            {
                ProductionList = OPDate;
                DataListCount = Convert.ToUInt32(OPDate.Count);
            }
            else
            {
                ProductionList = OPDate;
                DataListCount = 1;
            }

        }
        public ProductionViewModel2()
        {
            Init();
            //CylinderNo = GlobalVariables.CylinderNo.ToString();
            RegionList = new(MyDbContext.Instance.GetRegion());
            RegionList.Insert(0,new DataBase.Region() { Name = "全部" });
            Multi = new ObservableCollection<Help.UI.MultiComboBox.MultiCbxBaseData>();
            foreach (var item in CraftList)
            {
                Multi.Add(new Help.UI.MultiComboBox.MultiCbxBaseData { ID = item.Id, Name = item.Project, IsCheck = false });
            }




            SelectFilter = new DelegateCommand<object>((p) => { SelectFilter_Click(p); });

            SelectColumn = new DelegateCommand<object>((p) => { SelectColumn_Click(p); });//查询
            DetailColumn = new DelegateCommand<object>((p) => { DetailColumn_Click(p); });//明细
            ExportData = new DelegateCommand<object>((p) => { ExportData_Click(p); });//导出数据
            DataListPagingStartLengthChangeEvent += DataItemViewModel_DataListPagingStartLengthChangeEvent;



        }

    
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="param"></param>
        private void SelectColumn_Click(Object param)
        {
            Init();
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="param"></param>
        private async void ExportData_Click(Object param)
        {
         
            //找到要导出的文件的绝对路径或数据库信息
            using MyDbContext myDbContext = new();
            List<DataBase.DBmodels.ProductionData> productionData = OPDate;
            if (productionData != null)
            {
                // 创建一个 FolderBrowserDialog 对象
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

                // 显示选择文件夹对话框并获取结果
                //DialogResult result = folderBrowserDialog.ShowDialog();

                System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.Filter = "csv |*.csv";
                var result = sfd.ShowDialog();
                //if (result != System.Windows.Forms.DialogResult.Cancel)

                    // 处理对话框结果
                    if (result == DialogResult.OK)
                {
                    string targetFolderPath = folderBrowserDialog.SelectedPath;

                    //从数据库读取数据进行导出，这一部分没有判定框
                    var productionDataLogLists = OPDate;
                        CSVUtil util = new();
                        List<CSVData2> CSVDataList = new();
                        List<Border> borderList = new();

                        CSVDataList = productionDataLogLists.Select(x => x.ToCSVData2(x)).ToList();
                        string fileName = sfd.FileName;
                        string relativePath = Path.Combine("CSV", "", fileName);
                        string filePath = Path.Combine(targetFolderPath, fileName);
                        await util.WriteToCsvAsync(CSVDataList, borderList, filePath);
                        MessageBox.Show($"导出成功");
                    
                }
            }
            else
            {
                MessageBox.Show($"文件不存在");
            }


        }


        private void SelectFilter_Click(object param)
        {
            Multi.Clear();
            foreach (var item in CraftList)
            {
                if (item.CraftId == CraftId|| CraftId==0)
                {
                    Multi.Add(new Help.UI.MultiComboBox.MultiCbxBaseData { ID = item.Id, Name = item.Project, IsCheck = false });
                }
                
            }
        }
        /// <summary>
        /// 明细
        /// </summary>
        /// <param name="param"></param>
        private void DetailColumn_Click(Object param)
        {
            var paramss = param as DataBase.DBmodels.ProductionData;
            if (paramss != null)
            {
                Id = paramss.Id;
                Pages.Power.Production production = new Pages.Power.Production();
                production.Show();
            }
        }

        public class OkNgConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                int intValue = (int)value;
                return (intValue == 0) ? "Ok" : "NG";
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                string stringValue = (string)value;
                return (stringValue == "Ok") ? 0 : 1;
            }
        }

        #region   分页方法
        /// <summary>
        /// 数据总数
        /// </summary>
        private uint _dataListCount = 20;
        public uint DataListCount
        {
            get { return _dataListCount; }
            set
            {
                SetProperty(ref _dataListCount, value);
                RaisePropertyChanged("DataListCount");
            }
        }

        /// <summary>
        ///(分页事件) 用于界面绑定的 页面刷新事件
        /// </summary>
        public ICommand PageRefreshCmd
        {
            get
            {
                return new RelayCommand<Tuple<uint, uint>>(tuple =>
                {
                    if (DataListPagingStartLengthChangeEvent != null)
                    {
                        DataListPagingStartLengthChangeEvent(tuple.Item1,
                                                             tuple.Item2);
                    }
                });
            }
        }
        /// <summary>
        /// 数据列表刷新的   请求事件，参数-startIndex,length
        /// </summary>
        public event Action<uint, uint> DataListPagingStartLengthChangeEvent;
        private void DataItemViewModel_DataListPagingStartLengthChangeEvent(uint start, uint length)
        {
            if (ProductionList != null)
            {
                //从新给数据源赋值
                var len = (int)length;
                int star = (int)(start - 1) * len;
                ProductionList = OPDate.Skip(star).Take(len).ToList();
            }

        }
        #endregion
    }

}
